package nix.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String methodName = request.getParameter("method");
		if (methodName == null || methodName.trim().isEmpty()) {
			throw new RuntimeException("未指定method参数！");
		}
		
		Method method = null;
		try {
			method = this.getClass().getMethod(methodName,
					HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("方法: " + methodName
					+ "(HttpServletRequest, HttpServletResponse) 不存在！");
		}
		try {
			String result = (String) method.invoke(this, request, response);
			if (result == null || result.trim().isEmpty()) {
				return;
			}
			if (result.contains(":")) {
				String[] rsts = result.split(":");
				if (rsts[0].equalsIgnoreCase("r")) {
					response.sendRedirect(request.getContextPath() + rsts[1]);
				} else if (rsts[0].equalsIgnoreCase("f")) {
					request.getRequestDispatcher(rsts[1]).forward(request,
							response);
				} else {
					throw new RuntimeException("暂未支持的处理！");
				}
			} else {
				response.sendRedirect(request.getContextPath() + result);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}
}
